package org.openmrs.web.controller.user;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.openmrs.Attribute;
import org.openmrs.web.WebConstants;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class AttributeFormController extends SimpleFormController {
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		//		binder.registerCustomEditor(Policy.class, new PolicyEditor());
		binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
	        BindException errors) throws Exception {
		HttpSession httpSession = request.getSession();
		String attributeName = request.getParameter("attrib_name");
		String attributeType = request.getParameter("attrib_type");
		String attributeDataType = request.getParameter("data_type");
		String userName = request.getParameter("user_name");
		
		String first = request.getParameter("firstTime");
		Object firstTime = request.getAttribute("firstTime");
		
		System.out.println("First " + first);
		System.out.println("First Time " + firstTime);
		
		System.out.println("Name " + attributeName);
		System.out.println("Type " + attributeType);
		System.out.println("Data Type " + attributeDataType);
		System.out.println("User Name " + userName);
		
		String errorResponse = "";
		if (attributeType == null || attributeType.isEmpty()) {
			errorResponse = "Invalid Attribute Type";
		}
		
		if (attributeDataType == null || attributeDataType.isEmpty()) {
			errorResponse = "Invalid Attribute Data Type";
		}
		
		String view = null;
		if (errorResponse.isEmpty()) {
			view = getSuccessView();
		} else {
			httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, errorResponse);
			view = getFormView();
		}
		
		return new ModelAndView(new RedirectView(view));
	}
	
	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		Attribute attribute = new Attribute();
		return attribute;
	}
	
}
